package com.luzhikun.jsptest.myjsp;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * ClassName: DBCPUtil
 * Description:
 * date: 2021/4/27 12:32
 *
 * @author luzhikun
 * @since JDK 1.8
 */

/**
 * 数据库连接池工具类
 */
public class DBCPUtil {
    //创建数据源对象
    public static BasicDataSource bs;

    /*
     * 获取连接
     *
     * */
    public static Connection getConnection() {
        //创建连接对象
        Connection conn = null;
        if (bs == null) {
            //加载属性文件
            try {
                //创建属性集
                Properties pro = new Properties();
                //记住  记住 记住  将配置文件放在resources中 直接写配置文件名称就可以了
                InputStream resourceAsStream = DBCPUtil.class.getClassLoader().getResourceAsStream("mysql.dbcp.properties");
                pro.load(resourceAsStream);
                bs = BasicDataSourceFactory.createDataSource(pro);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            conn = bs.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭数据库连接操作
     */
    public static void closeAll(ResultSet rs, PreparedStatement pst, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 提供一个重载的关闭操作
     */
    public static void closeAll(PreparedStatement pst, Connection conn) {
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }


}
